package com.longkey.workflow.client.selector
{
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.system.IME;
	
	import mx.collections.ArrayList;
	import mx.controls.LinkButton;
	
	import spark.components.BorderContainer;
	import spark.components.Button;
	import spark.components.DataGrid;
	import spark.components.Group;
	import spark.components.HGroup;
	import spark.components.Label;
	import spark.components.TextInput;
	import spark.components.gridClasses.GridColumn;
	import spark.layouts.VerticalLayout;
	
	import org.longkey.portal.Portal;
	
	public class DataGridSelector extends Group implements ISelector
	{
		private var custId:String;
		private var selectedList:ArrayList;
		private var selectedMap:Object;
		
		private var command:String;
		private var pageLimit:int = 10;
		private var valueField:String;
		private var labelField:String;
		
		private var columns:Array;
		private var radio:Boolean = false;
		
		private var selected:Label;
		private var query:TextInput;
		
		private var showGroup:HGroup;
		private var searchGroup:HGroup;
		private var dataGroup:Group;
		private var dataGrid:DataGrid;
		private var checkboxColumn:CheckBoxGridColumn;
		private var pageGroup:HGroup;
		
		private var page:Label;
		private var gotoPage:TextInput;
		private var currentPage:int = 1;
		private var totalPage:int = 1;
		
		[Embed(source="img/arrow_left_double_24.png")]
		private var firstPageIcon:Class;
		[Embed(source="img/arrow_left_24.png")]
		private var prePageIcon:Class;
		[Embed(source="img/arrow_right_24.png")]
		private var nextPageIcon:Class;
		[Embed(source="img/arrow_right_double_24.png")]
		private var lastPageIcon:Class;
		[Embed(source="img/arrow_jump_24.png")]
		private var jumpPageIcon:Class;
		
		public function DataGridSelector()
		{
			super();
			
			this.selectedList = new ArrayList();
			this.selectedMap = new Object();
			
			this.percentHeight = 100;
			this.percentWidth = 100;
			var lay:VerticalLayout = new VerticalLayout();
			lay.gap = 10;
			lay.clipAndEnableScrolling = true;
			lay.paddingTop = 10;
			this.layout = lay;
			
			
			showGroup = new HGroup();
			showGroup.percentWidth = 100;
			showGroup.height = 30;
			showGroup.horizontalAlign = "left";
			showGroup.verticalAlign = "middle";
			var prelab:Label = new Label();
			prelab.text = "选中：";
			this.selected = new Label();
			this.selected.text = "";
			showGroup.addElement(prelab);
			showGroup.addElement(this.selected);
			this.addElement(showGroup);
			
			searchGroup = new HGroup();
			searchGroup.percentWidth = 100;
			searchGroup.horizontalAlign = "left";
			searchGroup.verticalAlign = "middle";
			prelab = new Label();
			prelab.text = "查询：";
			query = new TextInput();
			query.minWidth = 200;
			query.focusEnabled = true;
			query.imeMode = "CHINESE";
			IME.enabled = true;
			
			var querybtn:Button = new Button();
			querybtn.label = "搜索";
			querybtn.addEventListener(MouseEvent.CLICK, queryBtnClickHandle);
			var clearbtn:Button = new Button();
			clearbtn.label = "清空";
			clearbtn.addEventListener(MouseEvent.CLICK, clearBtnClickHandle);
			searchGroup.addElement(prelab);
			searchGroup.addElement(query);
			searchGroup.addElement(querybtn);
			searchGroup.addElement(clearbtn);
			this.addElement(searchGroup);
			
			dataGroup = new Group();
			dataGroup.percentHeight = 100;
			dataGroup.percentWidth = 100;
			this.addElement(dataGroup);
			
			pageGroup = new HGroup();
			pageGroup.percentWidth = 100;
			pageGroup.gap = 0;
			pageGroup.horizontalAlign = "right";
			pageGroup.verticalAlign = "middle";
			pageGroup.paddingRight = 20;
			var firstPage:LinkButton = new LinkButton();
			firstPage.setStyle("icon", firstPageIcon);
			firstPage.addEventListener(MouseEvent.CLICK, firstPageHandle);
			var prePage:LinkButton = new LinkButton();
			prePage.setStyle("icon", prePageIcon);
			prePage.addEventListener(MouseEvent.CLICK, prePageHandle);
			page = new Label();
			page.text = this.currentPage + "/" + this.totalPage;
			var nextPage:LinkButton = new LinkButton();
			nextPage.setStyle("icon", nextPageIcon);
			nextPage.addEventListener(MouseEvent.CLICK, nextPageHandle);
			var lastPage:LinkButton = new LinkButton();
			lastPage.setStyle("icon", lastPageIcon);
			lastPage.addEventListener(MouseEvent.CLICK, lastPageHandle);
			this.gotoPage = new TextInput();
			this.gotoPage.width = 30;
			var jumpPage:LinkButton = new LinkButton();
			jumpPage.setStyle("icon", jumpPageIcon);
			jumpPage.addEventListener(MouseEvent.CLICK, jumpPageHandle);
			pageGroup.addElement(firstPage);
			pageGroup.addElement(prePage);
			pageGroup.addElement(page);
			pageGroup.addElement(nextPage);
			pageGroup.addElement(lastPage);
			pageGroup.addElement(this.gotoPage);
			pageGroup.addElement(jumpPage);
			this.addElement(pageGroup);
			
//			this.query.addEventListener(Event.ADDED_TO_STAGE, initQueryKeyboardEventListener);
			this.query.addEventListener(KeyboardEvent.KEY_DOWN, queryKeyboardHandle);
			this.gotoPage.addEventListener(KeyboardEvent.KEY_DOWN, gotoKeyboardHandle);
		}
		
//		private function initQueryKeyboardEventListener(event:Event):void{
//			this.query.addEventListener(KeyboardEvent.KEY_DOWN, queryKeyboardHandle);
//		}
		
		private function queryKeyboardHandle(event:KeyboardEvent):void{
			switch(event.keyCode){
				case 13: //enter
					this.exec(this.query.text, 1);
					break;
				default:
					break;
			}
		}
		
		private function gotoKeyboardHandle(event:KeyboardEvent):void{
			switch(event.keyCode){
				case 13: //enter
					var num:Number = parseInt(this.gotoPage.text);
					if(num){
						if(num < 1)
							num = 1;
						else if(num > this.totalPage)
							num = this.totalPage;
						this.exec(this.query.text, int(num));
					}
					else{
						this.gotoPage.text = "";
					}
					break;
				default:
					break;
			}
		}
		
		private function firstPageHandle(event:MouseEvent):void{
			if(this.currentPage == 1)
				return;
			this.exec(this.query.text, 1);
		}
		
		private function prePageHandle(event:MouseEvent):void{
			if(this.currentPage == 1)
				return;
			this.exec(this.query.text, this.currentPage-1);
		}
		
		private function nextPageHandle(event:MouseEvent):void{
			if(this.currentPage == this.totalPage)
				return;
			this.exec(this.query.text, this.currentPage+1);
		}
		
		private function lastPageHandle(event:MouseEvent):void{
			if(this.currentPage == this.totalPage)
				return;
			this.exec(this.query.text, this.totalPage);
		}
		
		private function jumpPageHandle(event:MouseEvent):void{
			var num:Number = parseInt(this.gotoPage.text);
			if(num){
				if(num < 1)
					num = 1;
				else if(num > this.totalPage)
					num = this.totalPage;
				this.exec(this.query.text, int(num));
			}
			else{
				this.gotoPage.text = "";
				return;
			}
		}
		
		private function queryBtnClickHandle(event:MouseEvent):void{
			this.exec(this.query.text, 1);
		}
		
		private function clearBtnClickHandle(event:MouseEvent):void{
			this.selected.text = "";
			this.selectedList.removeAll();
			this.selectedMap = new Object();
			if(this.dataGrid.dataProviderLength > 0){
				var list:ArrayList = new ArrayList();
				for(var i:int = 0; i < this.dataGrid.dataProviderLength; i++){
					var data:Object = this.dataGrid.dataProvider.getItemAt(i);
					data["selected"] = "0"; 
					list.addItem(data);
				}
				this.dataGrid.dataProvider = list;
			}
		}
		
		private function exec(querystr:String, page:int):void{
			var params:Object = new Object();
			params["page"] = page;
			params["querystr"] = querystr;
			params["checkboxField"] = "selected";
			params["valueField"] = this.valueField;
			params["labelField"] = this.labelField;
			params["pageLimit"] = this.pageLimit;
			params["columns"] = this.columns;
			params["selectedValues"] = this.selectedList;
			Portal.execjava(prepareDataProvider, this.command, params, this.custId);
		}
		
		private function prepareDataProvider(result:Object):void{
			if(result == null)
				return;
			this.currentPage = parseInt(result["page"]);
			this.totalPage = parseInt(result["totalPage"]);
			this.refreshPageLabel();
			if(this.selectedList.length > 0){
				if(!this.selectedMap.hasOwnProperty(this.selectedList.getItemAt(0) as String)){
					if(result.hasOwnProperty("selectedLables")){
						var ary:Array = result["selectedLables"] as Array;
						this.selected.text = ary.join();
					}
				}
			}
			var dataList:Array = result["dataList"] as Array;
			this.dataGrid.dataProvider = new ArrayList(dataList);
		}
		
		public function init(command:String, columnDefines:Array, valueField:String, labelField:String, radio:Boolean=false, pageLimit:int=10):void{
			this.command = command;
			this.columns = new Array();
			this.valueField = valueField;
			this.labelField = labelField;
			this.radio = radio;
			this.pageLimit = pageLimit;
			
			this.dataGrid = new DataGrid();
			dataGrid.percentHeight = 100;
			dataGrid.percentWidth = 100;
			dataGrid.columns = new ArrayList();
			
			this.checkboxColumn = new CheckBoxGridColumn();
			checkboxColumn.editable = false;
			checkboxColumn.checkAllEnable = !this.radio;
			checkboxColumn.dataField = "selected";
			checkboxColumn.headerText = "";
			checkboxColumn.width = 30;
			checkboxColumn.resizable = false;
			checkboxColumn.addEventListener("allCheckChange", allCheckChangeHandle);
			checkboxColumn.addEventListener("rowCheckChange", rowCheckChangeHandle);
			this.dataGrid.columns.addItem(checkboxColumn);
			
			for(var i:int = 0; i < columnDefines.length; i++){
				var cd:ColumnDefine = columnDefines[i] as ColumnDefine;
				this.columns.push(cd.key);
				if(!cd.display)
					continue;
				var col:GridColumn = new GridColumn();
				col.dataField = cd.key;
				col.editable = false;
				
				col.headerText = cd.label;
				if(cd.width > 0)
					col.width = cd.width;
				this.dataGrid.columns.addItem(col);
			}
			
			this.dataGroup.addElement(this.dataGrid);
		}
		
		public function clear():void
		{
			this.selected.text = "";
			this.custId = null;
			this.selectedList.removeAll();
			this.selectedMap = new Object();
			if(this.dataGrid.dataProviderLength > 0)
				this.dataGrid.dataProvider.removeAll();
		}
		
		
		
		private function allCheckChangeHandle(event:CheckEvent):void{
			var list:ArrayList = new ArrayList();
			if(event.selected){
				for(var i:int = 0; i < this.dataGrid.dataProviderLength; i++){
					var data:Object = this.dataGrid.dataProvider.getItemAt(i);
					data["selected"] = "1";
					list.addItem(data);
					var val:String = data[this.valueField] as String;
					if(val != null && !this.selectedMap.hasOwnProperty(val)){
						var lab:String = data[this.labelField] as String;
						this.selectedMap[val] = lab;
						this.selectedList.addItem(val);
					}
				}
			}
			else{
				for(i = 0; i < this.dataGrid.dataProviderLength; i++){
					data = this.dataGrid.dataProvider.getItemAt(i);
					data["selected"] = "0";
					list.addItem(data);
					val = data[this.valueField] as String;
					if(val != null && this.selectedMap.hasOwnProperty(val)){
						this.selectedList.removeItem(val);
						delete this.selectedMap[val];
					}
				}
			}
			this.dataGrid.dataProvider = list;
			this.refreshSelectedLabel();
		}
		
		private function rowCheckChangeHandle(event:CheckEvent):void{
			var val:String = event.rowData[this.valueField] as String;
			if(event.selected){
				if(this.radio){
					this.selectedMap = new Object();
					this.selectedList.removeAll();
					var list:ArrayList = new ArrayList();
					for(var i:int = 0; i < this.dataGrid.dataProviderLength; i++){
						var data:Object = this.dataGrid.dataProvider.getItemAt(i);
						if(i != event.rowIndex){
							data["selected"] = "0";
						}
						list.addItem(data);
					}
					this.dataGrid.dataProvider = list;
				}
				if(!this.selectedMap.hasOwnProperty(val)){
					var lab:String = event.rowData[this.labelField] as String;
					this.selectedList.addItem(val);
					this.selectedMap[val] = lab;
				}
			}
			else{
				if(this.selectedMap.hasOwnProperty(val)){
					this.selectedList.removeItem(val);
					delete this.selectedMap[val];
				}
				
			}
			this.refreshSelectedLabel();
		}
		
		private function refreshSelectedLabel():void{
			var ary:Array = new Array();
			for(var i:int = 0; i < this.selectedList.length; i++){
				var val:String = this.selectedList.getItemAt(i) as String;
				ary.push(this.selectedMap[val] as String);
			}
			this.selected.text = ary.join();
		}
		
		private function refreshPageLabel():void{
			this.page.text = this.currentPage + "/" + this.totalPage;
		}
		
		
		public function load(selectedValues:String=null, custId:String=null):void
		{
			this.custId = custId;
			if(selectedValues != null && selectedValues.length > 0){
				var ary:Array = selectedValues.split(",");
				for(var val:String in ary){
					if(val.length == 0)
						continue;
					this.selectedList.addItem(val);
					this.selectedMap[val] = null;
				}
			}
			this.exec(null, 1);
		}
		
		public function submit():Object
		{
			var ret:Array = new Array();
			ret.push(this.selectedList.toArray().join(), this.selected.text);
			return ret;
		}
		
		
	}
}